import { Button, Select } from 'antd';
import React, { Component } from 'react';
import CodeCustom from '../../../utils/codeMirror/codeMirror';
import Scss from "./index.module.scss"
import DemoList from "./htmlDemo.json"

const { Option } = Select
const template = {
	html: `<!DOCTYPE html>
	<html lang="en">
	<head>
		<meta charset="UTF-8">
		<meta http-equiv="X-UA-Compatible" content="IE=edge">
		<meta name="viewport" content="width=device-width, initial-scale=1.0">
		<title>Document</title>
	</head>
	<body>
	<div></div>
	<script>
	
	</script>
	</body>
	</html>`,
	css: `*{
		margin:0;
		padding:0;
	}`
}
interface State {
	selectValue: string
}
interface Props {

}
class MirrorCode extends Component<Props, State> {
	htmlRef: any = React.createRef()   //html
	cssRef: any = React.createRef()
	constructor(props) {
		super(props)
		this.state = {
			selectValue: null
		}

	}
	componentDidMount = () => {

	}

	//重置
	resetHTML = () => {
		this.htmlRef.current.setValue(template.html)
		this.cssRef.current.setValue(template.css)
		this.setState({ selectValue: null })
	}

	//运行
	runCode = () => {
		let html = this.htmlRef.current.getValue()
		let css = this.cssRef.current.getValue()
		// 拼接css代码
		let src: string = html;
		if (css) {
			css = '<style>' + css + '</style>';
			src = src.replace('<body>', css + '</body>');
		}
		this.htmlRef.current.setValue(src)
		this.htmlRef.current.codeRun("codeShow")
	}

	//切换demo示例
	changeHTML = (value, option) => {
		fetch(option.src).then(response => response.text()).then(htmlString => {
			this.htmlRef.current.setValue(htmlString)
			this.cssRef.current.setValue("")
		})
		this.setState({ selectValue: value })
	}

	render() {
		const { selectValue } = this.state
		return (
			<div className={Scss.codeMirror}>
				<div className='left'>
					<div className='code'>
						<div className='codename'>
							<Select
								style={{ width: "150px", position: "absolute", left: "3px", top: "2px" }}
								onSelect={this.changeHTML}
								placeholder="html案例"
								value={selectValue}
							>
								{DemoList.map((item, index) => {
									return <Option key={index} value={item.name} src={item.src}>{item.name}</Option>
								})}
							</Select>
							HTML代码
							<Button style={{ position: "absolute", right: "80px", top: "2px" }} onClick={() => this.resetHTML()}>重置</Button>
							<Button style={{ position: "absolute", right: "3px", top: "2px" }} onClick={() => this.runCode()}>运行</Button>
						</div>
						<CodeCustom ref={this.htmlRef} mode="text/javascript" type="html" />
					</div>
					<div className='code'>
						<div className='codename'>CSS代码</div>
						<CodeCustom ref={this.cssRef} mode="text/css" type="css" />
					</div>
				</div>
				<iframe className='right' id="codeShow"></iframe>
			</div>
		);
	}
}

export default MirrorCode;